<?php defined('SYSPATH') or die('No direct script access.');

class Model_Sitemap
{ 
    protected static $_links_per_file = 10000; 
 
    public static function generate_sitemap()
    {
        $regions = ORM::factory('region')
                    ->find_all()
                    ->as_array();
        $regions[] = null;
        
        // чистим папку с частями сайтмапов
        self::_clear_sitemap_folder($regions);
            
        // сначала генерим все категории с фильтрами
        $n    = 0;
        $urls = array();
        
        $categories = ORM::factory('category')
                        ->where('url', 'NOT LIKE', 'cat-%')
                        ->find_all();    
        foreach ($regions as $region) {
            foreach ($categories as $category) {            
                self::_try_write_file($n, $urls, 'filter', $region);
                $n++;
                $urls[] = Helper_Index::catalog_url($category, null, null, null, false);
                
                $tags = ORM::factory('tag')->get_tags_by_category($category, null, true);
                foreach ($tags as $tag) {
                    self::_try_write_file($n, $urls, 'filter', $region);
                    $n++;
                    $urls[] = Helper_Index::catalog_url($category, $tag, null, null, false);
                }    
            }
            
            if (count($urls)) {
                self::_write_file($urls, $n, 'filter', $region);    
            }
            $n    = 0;
            $urls = array();
        }      
        
        
        // потом доступные товары
        /*$part = 1;
        do {
            $limit  = self::$_links_per_file;
            $offset = ($part - 1) * $limit;
            $part++;
            
            $products = ORM::factory('product')
                            ->where('is_available', '=', 1)
                            ->order_by('id', 'ASC')
                            ->offset($offset)
                            ->limit($limit)
                            ->find_all();
                            
            $urls = array();
            foreach ($products as $product) {
                $urls[] = Helper_Index::product_url($product, false);    
            }
            if (count($urls)) {
                self::_write_file($urls, $offset + $limit, 'product');    
            } 
        } while (count($products)); */
        
        // генерим основные сайтмапы
        self::_generate_main_sitemaps($regions);  
    }
    
    protected static function _clear_sitemap_folder($regions)
    {
        foreach ($regions as $region) {
            $directory = APPPATH.'../sitemaps/';
            if ($region) {
                $directory .= $region->url.'/';
            }
            if (is_dir($directory)) {
                $files     = scandir($directory);
                foreach ($files as $file) {
                    if ($file == '.' || $file == '..') {
                        continue;
                    }
                    if (is_file($directory.$file)) {
                        unlink($directory.$file); 
                    }   
                } 
            }
        }  
    }
    
    protected static function _try_write_file($n, &$urls, $prefix = 'filter', $region = null)
    {
        if ($n && ($n % self::$_links_per_file == 0)) {
            self::_write_file($urls, $n, $prefix, $region);
            
            $urls = array();        
        }    
    }
    
    protected static function _write_file($urls, $n, $prefix = 'filter', $region = null)
    {
        $number_file = floor(($n - 1) / self::$_links_per_file) + 1;      
        $directory   = APPPATH.'../sitemaps/';
        $region_url = '';
        if ($region) {
            $directory   .= $region->url.'/';
            if (!is_dir($directory)) {
                mkdir($directory);
            } 
            $region_url = $region->url.'.'; 
        }
        $filename    = $directory.$prefix.$number_file.'.xml';
        
        $handler = fopen($filename, 'w');
        fputs($handler, "<?xml version='1.0' encoding='UTF-8'?>\r\n<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\r\n");
        foreach ($urls as $url) {
            fputs($handler, "\t<url>\r\n\t\t<loc>http://{$region_url}cashbackdoc.com{$url}</loc>\r\n\t</url>\r\n");        
        }
        fputs($handler, "</urlset>");
        fclose($handler);
    }
    
    protected static function _generate_main_sitemaps($regions)
    {
        foreach ($regions as $region) {
            $directory = APPPATH.'../sitemaps/';
            $region_folder = '';
            $region_url = '';
            if ($region) {
                $directory .= $region->url.'/';
                $region_folder = $region->url.'/';
                $region_url = $region->url.'.';    
            }
            $_files    = scandir($directory);
            $files     = array();
            foreach ($_files as $file) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                if (is_file($directory.$file)) {
                    $files[] = $file; 
                }  
            }
            
            if ($region) {
                $sitemap = APPPATH.'../sitemap_'.$region->url.'.xml';    
            } else {
                $sitemap = APPPATH.'../sitemap.xml';   
            }
            $handler = fopen($sitemap, 'w'); 
            fputs($handler, "<?xml version='1.0' encoding='UTF-8'?>\r\n<sitemapindex xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\r\n");
            foreach ($files as $file) {
                fputs($handler, "\t<sitemap>\r\n\t\t<loc>http://{$region_url}cashbackdoc.com/sitemaps/{$region_folder}{$file}</loc>\r\n\t</sitemap>\r\n");        
            }
            fputs($handler, "</sitemapindex>");  
        }   
    }
}